﻿
var MAP_TAB = 2

$(function () {
    $("#myMap").width($(window).width() - 20).height($(window).height() - 70);


    $("#tabs").tabs();

    //$("#tabs").height($(window).height() - 25);
    $("#tabs").css("min-height", $(window).height() - 25);

    //$("#details").width($(window).width() - 20).height($(window).height() - 60);

    $("#tabs").tabs("select", MAP_TAB);
    setTimeout(function () { loadMap(); }, 1000);

    $("#tabs").tabs('destroy').tabs({ select: function (event, ui) { $(this).data("tabs").xhr = null; } });
    var nPrevTab = getCookie("PrevTab")
    $("#tabs").tabs("select", parseInt(nPrevTab));

    $("#tabs").bind('tabsselect', function (event, ui) {
        setCookie("PrevTab", ui.index, 1)
        if (ui.index == MAP_TAB) setTimeout(function () { loadMap(); }, 100);
    });

    //    $('#tabs')
    //    .bind('tabsload', function (event, ui) {

    $("#pnlAddressList").height($(window).height() - 160);

    //alert('Loading')

    $("span[class$='lblAddr']").css("cursor", "pointer").click(function () {
        $("#report_results").load("DetailData.aspx?DATA=" + this.attributes['Value'].value + "&COLOR=" + this.style.backgroundColor)
    });


    $("span[class$='lblAddr']").hover(
    /// <reference path="../ActiveProperties.aspx" />
       function () {
           $(this).append($("<span> ***</span>"));
       },
              function () {
                  $(this).find("span:last").remove();
              });
    //    });


    if (parent.reports == null) {
        alert('Wait...')
        printpreview()

        //           var x = confirm("Close Document?")
        //           window.close()
    }

    function printpreview() {
        var OLECMDID = 7;
        /* OLECMDID values: * 6 - print * 7 - print preview * 1 - open window * 4 - Save As */
        var PROMPT = 2; // 2 DONTPROMPTUSER 
        var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';

        this.document.body.insertAdjacentHTML('beforeEnd', WebBrowser);

        WebBrowser1.ExecWB(OLECMDID, PROMPT);
        WebBrowser1.outerHTML = "";
    }



});

var map;
function loadMap() {
try
{
    map = new VEMap('myMap');
    map.LoadMap();
    map.SetZoomLevel(11);
    //debugger;    
    var Addrs = $("#hdnAddress").val()
    map.Find(null, Addrs, null, null, 0, 1, true, true, true, true, setLocation);
    
    }
    catch(e){}

}

function setLocation(layer, resultsArray, places, hasMore, veErrorMessage) {
    map.SetMapStyle(VEMapStyle.BirdseyeHybrid);

    if (places == null) {
        alert((veErrorMessage == null) ? "Address not found!!!" : veErrorMessage);
        return;
    }

    var bestPlace = places[0];

    // Add pushpin to the *best* place
    var location = bestPlace.LatLong;

    var newShape = new VEShape(VEShapeType.Pushpin, location);

    var Addrs = $("#hdnAddress").val()
    var desc = "<b>Latitude:</b> " +
                          location.Latitude + "<br><b>Longitude:</b>"
                          + location.Longitude;
    newShape.SetDescription(Addrs);
    newShape.SetTitle(Addrs);
    map.AddShape(newShape);

}

function CreateExcelSheet() {
    if (confirm("Are you sure you want to create an Excel spreadsheet for '" + event.srcElement.nextSibling.data + " '?")) {
        var xls = new ActiveXObject("Excel.Application")
        var book1 = xls.Workbooks.Add

        book1.Sheets("Sheet1").Name = "SUBSCRIBERS"
        book1.Sheets("Sheet2").Name = "ELIGIBLES"
        book1.Sheets("Sheet3").Name = "NON-ELIGIBLES"

        GleanByColor(xls, book1, "NON-ELIGIBLES", "#ffffff", -1)
        GleanByColor(xls, book1, "ELIGIBLES", "#a4f368", 6878116)
        GleanByColor(xls, book1, "SUBSCRIBERS", "#47caff", 16763463)

        try {
            book1.SaveAs(event.srcElement.nextSibling.data)
        }
        catch (err) {
//            txt = "There was an error on this page.\n\n";
//            txt += "Error description: " + err.description + "\n\n";
//            txt += "If you have this file open, please close it and try again!\n\n";
//            txt += "Click OK to continue.\n\n";
//            alert(txt);
       }

        xls.visible = true
    }
}

function GleanByColor(xls, book1, psName, psColor, pnColor) {
    var theSheet = book1.Sheets(psName)
    theSheet.Activate
    var tbl = $("#grvAddressList")[0]
    var tblRows = tbl.rows
    var k = 0
    for (i = 0; i < tblRows.length; i++) {
        var y = tblRows[i].cells
        if (tblRows[i].firstChild.firstChild.style.backgroundColor == psColor) {
            theSheet.Cells(k + 1, 1).Value = y[0].innerText
            k += 1;
        }
    }
    xls.Range("A1").Select
    xls.Range(xls.Selection, xls.Selection.End(-4121)).Select
    xls.Selection.Columns.AutoFit
    if (pnColor > -1) { xls.Selection.Interior.Color = pnColor }
    xls.Range("A1").Select
}

function chkAddressType_Click() {
    var ctl = event.srcElement
    var ctlBgColor = ctl.parentElement.style.backgroundColor
    var i = 0;
    var spansAddrs = $("span[class$='lblAddr']");
    for (i = spansAddrs.length - 1; i >= 0; i--) {
        //if the span's backcolor is ctlBgColor then show or hide table row that contains the span
        if (spansAddrs[i].style.backgroundColor == ctlBgColor)
            spansAddrs[i].parentElement.parentElement.style.display = ctl.checked ? "" : "none"
    }
}


function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}


function saveScroll() {
    var x = document.documentElement.scrollLeft
    var y = document.documentElement.scrollTop
    setCookie("xy", x + "_" + y, 1)
}

function loadScroll() {
    var xy = getCookie("xy");
    if (!xy) return;
    var ar = xy.split("_");
    if (ar.length == 2) {
        document.documentElement.scrollLeft = parseInt(ar[0]),
            document.documentElement.scrollTop = parseInt(ar[1]);
    }
}

$(window).resize(function () {
    if ($(window).width() > 100 && $(window).height() > 200)
    {
        $("#myMap").width($(window).width() - 30).height($(window).height() - 80);
        $("#tabs").css("min-height", $(window).height() - 25);
        $("#pnlAddressList").height($(window).height() - 160)
    }
    //debugger;
    //$("#tabs").tabs("select", 3);
    //setTimeout(function () { loadMap(); }, 500);
});